﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static Semaphore _pool;

        private static int _padding;
        static void Main(string[] args)
        {
            _pool = new Semaphore(0, 3);

            for (int i = 1; i <= 5; i++)//创建并启动五个线程。
            {
                Thread t = new Thread(new ParameterizedThreadStart(Worker));

                t.Start(i);// 启动线程，传递数字。
            }

            Thread.Sleep(500);

            Console.WriteLine("主函数执行Release(3)");
            _pool.Release();//调用Release(3)会使信号量计数回其最大值，并允许等待的线程进入信号量，一次最多三个。

            Console.WriteLine("主函数关闭");
            Console.Read();
        }
        private static void Worker(object num)
        {
            while (true)
            {
                Console.WriteLine("222222222");
                Console.WriteLine("11111111111111");
                Console.WriteLine("");
                Console.WriteLine("线程 {0} 开始", num);
                _pool.WaitOne();

                //填充间隔，使输出更加有序。
                int padding = Interlocked.Add(ref _padding, 100);

                Console.WriteLine("线程 {0} 结束", num);

                Thread.Sleep(1000 + padding);

                Console.WriteLine("Thread {0} releases the semaphore.", num);
                Console.WriteLine("Thread {0} previous semaphore count: {1}", num, 1);
                _pool.Release();
            }
           
        }
    }
}
